package com.qf.homework.controller;

import com.qf.homework.entity.User;
import com.qf.homework.service.UserService;
import com.qf.homework.service.impl.UserServiceImpl;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userServiceImpl;

    @RequestMapping("/regist")
    public void registUser(User user, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String captcha =(String) req.getSession().getAttribute("captcha");
        String s = captcha.toLowerCase();
        String code = req.getParameter("code");
        String s1 = code.toLowerCase();
        //判断验证码是否正确
        if (s1.equals(s)){
            //判断用户名是否存在
            if (userServiceImpl.containsUsername(user.getUsername())){

                //用户名如果已存在就返回
                resp.getWriter().println("此用户已存在请重新注册");
                //因为用户名已存在，直接结束调用
                return;
            }else {
                if (userServiceImpl.verifyUser(user)) {
                    resp.sendRedirect("/sucess.html");
                }
            }
        }else {
            //此时验证码错误，返回
            resp.getWriter().println("验证码错误，请重新输入");
        }

    }

    @RequestMapping("/exist")
    public void existUser(String username,HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String result = null;
        if (userServiceImpl.containsUsername(username)) {
            result = "1";
        } else {
            result = "2";
        }
        resp.getWriter().println(result);
    }

}
